package net.lxch.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class SignUtil {
    public static String getSign(final Map<String, Object> params, String secret) {
        Map<String, Object> data = new TreeMap<>(params);
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[0]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (data.get(k) instanceof Boolean) {
                sb.append("&").append(k).append("=").append(data.get(k));
            }
            if (data.get(k) instanceof String && StringUtils.isNotBlank(data.get(k).toString())) {
                // 参数值为空，则不参与签名
                sb.append("&").append(k).append("=").append(data.get(k));
            }
        }
        sb.append(secret);
        return HashUtil.hash(sb.substring(1), HashUtil.ALGORITHM_MD5);
    }
}
